package com.szgz.platform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szgz.platform.model.TaskStep;
import com.szgz.platform.result.ApiResponse;
import com.szgz.platform.service.TaskStepService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 任务步骤控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/task-steps")
@CrossOrigin(origins = "*")
public class TaskStepController {

    @Autowired
    private TaskStepService taskStepService;

    /**
     * 分页查询任务的步骤列表
     *
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param taskId 任务ID
     * @param status 步骤状态
     * @return 分页结果
     */
    @GetMapping("/page")
    public ApiResponse<IPage<TaskStep>> getStepsByTaskId(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam Long taskId,
            @RequestParam(required = false) String status) {
        
        try {
            Page<TaskStep> page = new Page<>(pageNum, pageSize);
            IPage<TaskStep> result = taskStepService.getStepsByTaskId(page, taskId, status);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("分页查询任务步骤失败", e);
            return ApiResponse.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询任务的所有步骤（树形结构）
     *
     * @param taskId 任务ID
     * @param status 步骤状态
     * @return 步骤树形结构
     */
    @GetMapping("/tree")
    public ApiResponse<List<TaskStep>> getStepsTreeByTaskId(
            @RequestParam Long taskId,
            @RequestParam(required = false) String status) {
        
        try {
            List<TaskStep> result = taskStepService.getStepsTreeByTaskId(taskId, status);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("查询任务步骤树失败", e);
            return ApiResponse.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID查询步骤详情
     *
     * @param id 步骤ID
     * @return 步骤详情
     */
    @GetMapping("/{id}")
    public ApiResponse<TaskStep> getTaskStepById(@PathVariable Long id) {
        try {
            TaskStep taskStep = taskStepService.getById(id);
            if (taskStep == null) {
                return ApiResponse.fail("步骤不存在");
            }
            return ApiResponse.success(taskStep);
        } catch (Exception e) {
            log.error("查询步骤详情失败", e);
            return ApiResponse.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 创建任务步骤
     *
     * @param taskStep 步骤信息
     * @return 创建结果
     */
    @PostMapping
    public ApiResponse<Boolean> createTaskStep(@RequestBody TaskStep taskStep) {
        try {
            boolean result = taskStepService.createTaskStep(taskStep);
            if (result) {
                return ApiResponse.success("步骤创建成功", true);
            } else {
                return ApiResponse.fail("步骤创建失败");
            }
        } catch (Exception e) {
            log.error("创建任务步骤失败", e);
            return ApiResponse.fail("创建失败：" + e.getMessage());
        }
    }

    /**
     * 更新任务步骤
     *
     * @param id 步骤ID
     * @param taskStep 步骤信息
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public ApiResponse<Boolean> updateTaskStep(@PathVariable Long id, @RequestBody TaskStep taskStep) {
        try {
            taskStep.setId(id);
            boolean result = taskStepService.updateTaskStep(taskStep);
            if (result) {
                return ApiResponse.success("步骤更新成功", true);
            } else {
                return ApiResponse.fail("步骤更新失败");
            }
        } catch (Exception e) {
            log.error("更新任务步骤失败", e);
            return ApiResponse.fail("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除任务步骤
     *
     * @param id 步骤ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Boolean> deleteTaskStep(@PathVariable Long id) {
        try {
            boolean result = taskStepService.deleteTaskStep(id);
            if (result) {
                return ApiResponse.success("步骤删除成功", true);
            } else {
                return ApiResponse.fail("步骤删除失败");
            }
        } catch (Exception e) {
            log.error("删除任务步骤失败", e);
            return ApiResponse.fail("删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除任务步骤
     *
     * @param stepIds 步骤ID列表
     * @return 删除结果
     */
    @DeleteMapping("/batch")
    public ApiResponse<Boolean> batchDeleteTaskSteps(@RequestBody List<Long> stepIds) {
        try {
            boolean result = taskStepService.batchDeleteTaskSteps(stepIds);
            if (result) {
                return ApiResponse.success("批量删除成功", true);
            } else {
                return ApiResponse.fail("批量删除失败");
            }
        } catch (Exception e) {
            log.error("批量删除任务步骤失败", e);
            return ApiResponse.fail("删除失败：" + e.getMessage());
        }
    }

    /**
     * 更新步骤顺序
     *
     * @param id 步骤ID
     * @param newOrder 新顺序
     * @return 更新结果
     */
    @PutMapping("/{id}/order")
    public ApiResponse<Boolean> updateStepOrder(@PathVariable Long id, @RequestParam Integer newOrder) {
        try {
            boolean result = taskStepService.updateStepOrder(id, newOrder);
            if (result) {
                return ApiResponse.success("步骤顺序更新成功", true);
            } else {
                return ApiResponse.fail("步骤顺序更新失败");
            }
        } catch (Exception e) {
            log.error("更新步骤顺序失败", e);
            return ApiResponse.fail("更新失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新步骤顺序
     *
     * @param stepOrders 步骤顺序映射
     * @return 更新结果
     */
    @PutMapping("/batch/order")
    public ApiResponse<Boolean> batchUpdateStepOrders(@RequestBody Map<Long, Integer> stepOrders) {
        try {
            boolean result = taskStepService.batchUpdateStepOrders(stepOrders);
            if (result) {
                return ApiResponse.success("批量更新步骤顺序成功", true);
            } else {
                return ApiResponse.fail("批量更新步骤顺序失败");
            }
        } catch (Exception e) {
            log.error("批量更新步骤顺序失败", e);
            return ApiResponse.fail("更新失败：" + e.getMessage());
        }
    }

    /**
     * 查询步骤的子步骤
     *
     * @param parentStepId 父步骤ID
     * @param status 步骤状态
     * @return 子步骤列表
     */
    @GetMapping("/{parentStepId}/children")
    public ApiResponse<List<TaskStep>> getChildrenByParentId(
            @PathVariable Long parentStepId,
            @RequestParam(required = false) String status) {
        
        try {
            List<TaskStep> result = taskStepService.getChildrenByParentId(parentStepId, status);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("查询子步骤失败", e);
            return ApiResponse.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询步骤的父步骤
     *
     * @param stepId 步骤ID
     * @return 父步骤
     */
    @GetMapping("/{stepId}/parent")
    public ApiResponse<TaskStep> getParentByStepId(@PathVariable Long stepId) {
        try {
            TaskStep result = taskStepService.getParentByStepId(stepId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("查询父步骤失败", e);
            return ApiResponse.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询步骤的依赖步骤
     *
     * @param stepId 步骤ID
     * @return 依赖步骤列表
     */
    @GetMapping("/{stepId}/dependencies")
    public ApiResponse<List<TaskStep>> getDependenciesByStepId(@PathVariable Long stepId) {
        try {
            List<TaskStep> result = taskStepService.getDependenciesByStepId(stepId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("查询依赖步骤失败", e);
            return ApiResponse.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询步骤的依赖步骤
     *
     * @param stepId 步骤ID
     * @return 依赖步骤列表
     */
    @GetMapping("/{stepId}/dependents")
    public ApiResponse<List<TaskStep>> getDependentsByStepId(@PathVariable Long stepId) {
        try {
            List<TaskStep> result = taskStepService.getDependentsByStepId(stepId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("查询依赖步骤失败", e);
            return ApiResponse.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询任务中指定类型的步骤
     *
     * @param taskId 任务ID
     * @param stepType 步骤类型
     * @param status 步骤状态
     * @return 步骤列表
     */
    @GetMapping("/by-type")
    public ApiResponse<List<TaskStep>> getStepsByType(
            @RequestParam Long taskId,
            @RequestParam String stepType,
            @RequestParam(required = false) String status) {
        
        try {
            List<TaskStep> result = taskStepService.getStepsByType(taskId, stepType, status);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("查询指定类型步骤失败", e);
            return ApiResponse.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 统计任务的步骤数量
     *
     * @param taskId 任务ID
     * @param status 步骤状态
     * @return 步骤数量
     */
    @GetMapping("/count")
    public ApiResponse<Integer> countStepsByTaskId(
            @RequestParam Long taskId,
            @RequestParam(required = false) String status) {
        
        try {
            int result = taskStepService.countStepsByTaskId(taskId, status);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("统计步骤数量失败", e);
            return ApiResponse.fail("统计失败：" + e.getMessage());
        }
    }

    /**
     * 查询用户可访问的步骤
     *
     * @param taskId 任务ID
     * @param userId 用户ID
     * @param status 步骤状态
     * @return 可访问的步骤列表
     */
    @GetMapping("/accessible")
    public ApiResponse<List<TaskStep>> getAccessibleSteps(
            @RequestParam Long taskId,
            @RequestParam Long userId,
            @RequestParam(required = false) String status) {
        
        try {
            List<TaskStep> result = taskStepService.getAccessibleSteps(taskId, userId, status);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("查询可访问步骤失败", e);
            return ApiResponse.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 验证步骤依赖关系
     *
     * @param stepId 步骤ID
     * @return 验证结果
     */
    @GetMapping("/{stepId}/validate-dependencies")
    public ApiResponse<Boolean> validateStepDependencies(@PathVariable Long stepId) {
        try {
            boolean result = taskStepService.validateStepDependencies(stepId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("验证步骤依赖关系失败", e);
            return ApiResponse.fail("验证失败：" + e.getMessage());
        }
    }

    /**
     * 复制任务步骤到新任务
     *
     * @param sourceTaskId 源任务ID
     * @param targetTaskId 目标任务ID
     * @return 复制结果
     */
    @PostMapping("/copy")
    public ApiResponse<Boolean> copyTaskSteps(
            @RequestParam Long sourceTaskId,
            @RequestParam Long targetTaskId) {
        
        try {
            boolean result = taskStepService.copyTaskSteps(sourceTaskId, targetTaskId);
            if (result) {
                return ApiResponse.success("步骤复制成功", true);
            } else {
                return ApiResponse.fail("步骤复制失败");
            }
        } catch (Exception e) {
            log.error("复制任务步骤失败", e);
            return ApiResponse.fail("复制失败：" + e.getMessage());
        }
    }

    /**
     * 获取步骤的完整路径
     *
     * @param stepId 步骤ID
     * @return 步骤路径列表
     */
    @GetMapping("/{stepId}/path")
    public ApiResponse<List<TaskStep>> getStepPath(@PathVariable Long stepId) {
        try {
            List<TaskStep> result = taskStepService.getStepPath(stepId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("获取步骤路径失败", e);
            return ApiResponse.fail("获取失败：" + e.getMessage());
        }
    }

    /**
     * 检查步骤是否可见
     *
     * @param stepId 步骤ID
     * @param userId 用户ID
     * @return 是否可见
     */
    @GetMapping("/{stepId}/visible")
    public ApiResponse<Boolean> isStepVisible(
            @PathVariable Long stepId,
            @RequestParam Long userId) {
        
        try {
            boolean result = taskStepService.isStepVisible(stepId, userId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("检查步骤可见性失败", e);
            return ApiResponse.fail("检查失败：" + e.getMessage());
        }
    }

    /**
     * 检查步骤是否可跳过
     *
     * @param stepId 步骤ID
     * @param userId 用户ID
     * @return 是否可跳过
     */
    @GetMapping("/{stepId}/skippable")
    public ApiResponse<Boolean> isStepSkippable(
            @PathVariable Long stepId,
            @RequestParam Long userId) {
        
        try {
            boolean result = taskStepService.isStepSkippable(stepId, userId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("检查步骤可跳过性失败", e);
            return ApiResponse.fail("检查失败：" + e.getMessage());
        }
    }
} 